#!/bin/bash
le () { local n; n=$(printf "%08x" $(($1))); printf "%s" "${n:6:2}${n:4:2}${n:2:2}${n:0:2}"; }

convert_label_bmp () {
	local color="$1"
	local thelabel="$2"
	local thedest="$3"
	if [[ ! -f $thelabel ]]; then
		printf '# Disk label "%s" does not exist.\n' "$thelabel"
		return 1
	fi
	if [[ -z $thedest ]]; then
		thedest="$thelabel.bmp"
	fi

	local contents="$(xxd -c 99999999 -p "$thelabel")"
	local width=$((0x${contents:2:4}))
	local height=$((0x${contents:6:4}))
	echo "
		424d $(le $((14 + 40 + 16 + width * height * 4))) 00000000 $(le $((14 + 40 + 16)))
		$(le $((40 + 16))) $(le $width) $(le $height) 0100 2000 03000000
		$(le $((width * height * 4))) $(le 2835) $(le 2835) 0000000000000000
		0000FF00 00FF0000 FF000000 000000FF $(
			perl -pE 's/(.{'$(($width * 2))'})/$1\n/g;' <<< "${contents:10}" |
			perl -E 'print reverse <>' |
			color=$color perl -E '
				my %con = qw(
					00 00 f6 11 f7 22 2a 33 f8 44 f9 55 55 66 fa 77
					fb 88 80 99 fc aa fd bb ab cc fe dd ff ee d6 ff
				);
				while (<>) { s/(\w\w)/
					substr($ENV{color},4,2) . substr($ENV{color},2,2) . substr($ENV{color},0,2) . $con{$1}
					/eg; print $_;
				}
			'
		)
	" | xxd -p -r > "$thedest"
}


#
# convert_label_bmp "FF0000" "$thelabel" /tmp/label_red.bmp
# convert_label_bmp "00FF00" "$thelabel" /tmp/label_green.bmp
# convert_label_bmp "0000FF" "$thelabel" /tmp/label_blue.bmp
# convert_label_bmp "FFFFFF" "$thelabel" /tmp/label_white.bmp # for dark mode
# convert_label_bmp "000000" "$thelabel" /tmp/label_black.bmp # for light mode

convert_label_bmp "$1" "$2" "$3"
